package com.medical.blood.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.medical.blood.entity.MessageLog;
import com.medical.blood.entity.User;
import com.medical.blood.mapper.MessageLogMapper;
import com.medical.blood.mapper.UserMapper;
import me.chanjar.weixin.miniapp.api.WxMaService;
import me.chanjar.weixin.miniapp.bean.WxMaTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class MessagePushService {
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private MessageLogMapper messageLogMapper;
    @Autowired
    private UserMapper userMapper;

    // 注入模板ID
    @Value("${wx.miniapp.template.result_notify}")
    private String resultNotifyTemplateId;
    @Value("${wx.miniapp.template.device_fault}")
    private String deviceFaultTemplateId;
    @Value("${wx.miniapp.template.appointment_success}")
    private String appointmentSuccessTemplateId;

    /**
     * 发送检测结果通知（用户）
     */
    public void sendResultNotify(Long userId, String sampleNo, String reportTime) {
        User user = userMapper.selectById(userId);
        if (user == null) return;

        // 1. 构建消息日志
        MessageLog log = new MessageLog();
        log.setUserId(userId);
        log.setMessageType("结果通知");
        log.setTemplateId(resultNotifyTemplateId);
        log.setOpenid(user.getOpenid());
        log.setSendStatus("未发送");

        try {
            // 2. 构建模板消息
            WxMaTemplateMessage msg = WxMaTemplateMessage.builder()
                    .toUser(user.getOpenid())
                    .templateId(resultNotifyTemplateId)
                    .build();

            // 模板数据（需与小程序模板关键词对应）
            Map<String, String> data = new HashMap<>();
            data.put("keyword1", sampleNo); // 样本编号
            data.put("keyword2", reportTime); // 报告时间
            data.put("keyword3", "点击查看详情"); // 提示
            msg.setData(data);

            // 3. 调用微信API发送
            String msgId = wxMaService.getTemplateMsgService().sendTemplateMsg(msg);

            // 4. 更新日志
            log.setSendStatus("已发送");
            log.setSendTime(new Date());
            log.setContent(data.toString());
        } catch (Exception e) {
            log.setSendStatus("失败");
            log.setContent("发送失败：" + e.getMessage());
        }
        messageLogMapper.insert(log);
    }

    /**
     * 发送设备故障提醒（管理员）
     */
    public void sendDeviceFaultWarning(String deviceId, String faultDesc) {
        // 获取管理员openid（假设管理员用户admin_flag=1）
        User admin = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getAdminFlag, 1)
                .last("LIMIT 1"));
        if (admin == null) return;

        MessageLog log = new MessageLog();
        log.setIsAdmin(1);
        log.setMessageType("设备故障");
        log.setTemplateId(deviceFaultTemplateId);
        log.setOpenid(admin.getOpenid());
        log.setSendStatus("未发送");

        try {
            WxMaTemplateMessage msg = WxMaTemplateMessage.builder()
                    .toUser(admin.getOpenid())
                    .templateId(deviceFaultTemplateId)
                    .build();

            Map<String, String> data = new HashMap<>();
            data.put("keyword1", deviceId); // 设备编号
            data.put("keyword2", faultDesc); // 故障描述
            msg.setData(data);

            wxMaService.getTemplateMsgService().sendTemplateMsg(msg);
            log.setSendStatus("已发送");
            log.setSendTime(new Date());
        } catch (Exception e) {
            log.setSendStatus("失败");
        }
        messageLogMapper.insert(log);
    }

    /**
     * 发送预约成功通知（用户）
     */
    public void sendAppointmentSuccess(Long userId, String appointTime, String deviceLoc) {
        User user = userMapper.selectById(userId);
        if (user == null) return;

        MessageLog log = new MessageLog();
        log.setUserId(userId);
        log.setMessageType("预约成功");
        log.setTemplateId(appointmentSuccessTemplateId);
        log.setOpenid(user.getOpenid());
        log.setSendStatus("未发送");

        try {
            WxMaTemplateMessage msg = WxMaTemplateMessage.builder()
                    .toUser(user.getOpenid())
                    .templateId(appointmentSuccessTemplateId)
                    .build();

            Map<String, String> data = new HashMap<>();
            data.put("keyword1", appointTime); // 预约时间
            data.put("keyword2", deviceLoc); // 设备位置
            msg.setData(data);

            wxMaService.getTemplateMsgService().sendTemplateMsg(msg);
            log.setSendStatus("已发送");
            log.setSendTime(new Date());
        } catch (Exception e) {
            log.setSendStatus("失败");
        }
        messageLogMapper.insert(log);
    }
}